/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 62536
 * Date: 2024-06-10
 * Time: 9:13
 */
public class Solution {
    public static int minFallingPathSum(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] dp = new int[m+1][n+2];

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if(j == n){
                    dp[i][j] = matrix[i-1][j-1] + Math.min(dp[i-1][j-1],dp[i-1][j]);
                } else if (j == 1) {
                    dp[i][j] = matrix[i-1][j-1] + Math.min(dp[i-1][j+1],dp[i-1][j]);
                } else {
                    int x = Math.min(dp[i-1][j-1],dp[i-1][j]);
                    dp[i][j] = matrix[i-1][j-1] + Math.min(x,dp[i-1][j+1]);
                }

            }
        }
        int x = dp[m][n];
        for (int i = 1; i < n; i++) {
            if(dp[m][i] < x){
                x = dp[m][i];
            }
        }
        return x;
    }

    public static void main(String[] args) {
        int[][] m = {{2,1,3},{6,5,4},{7,8,9}};
        int i = minFallingPathSum(m);
    }
}
